package com.ruoyi.chat.controller;

import com.ruoyi.chat.service.impl.MinioService;
import io.minio.GetObjectArgs;
import io.minio.MinioClient;
import io.minio.StatObjectArgs;
import io.minio.StatObjectResponse;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;


import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Calendar;

@Controller
@RequestMapping("/chat/File")
public class FileController {
    @Autowired
    MinioClient client;
    @RequestMapping("/download/{fileprefix}/{filename}")
    public void downloadFiles(@PathVariable("filename") String filename,@PathVariable("fileprefix") String fileprefix, HttpServletResponse httpResponse) {
        System.out.println(filename);
        String bucket = null;
//        Calendar rightNow = Calendar.getInstance();
//        Integer year = rightNow.get(Calendar.YEAR);
//        Integer month = rightNow.get(Calendar.MONTH) + 1; //第一个月从0开始，所以得到月份＋1
//        Integer day = rightNow.get(Calendar.DAY_OF_MONTH);
//        bucket = year + "-" + month;
        InputStream in =  null;
        try {
            StatObjectResponse stat = client.statObject(StatObjectArgs.builder().bucket(fileprefix).object(filename).build());
            httpResponse.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
            httpResponse.setContentType(stat.contentType());
            //文件下载
            in = client.getObject(GetObjectArgs.builder().bucket(fileprefix).object(filename).build());
            IOUtils.copy(in,httpResponse.getOutputStream());
        } catch (Exception ex) {

        }
    }
}
